package com.samsung.sharepoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

/* This class is used to send a file */

public class FileClientService extends Service {

	Socket fileSocket;
	String SERVERIP = "192.168.43.8";
	File file;
	String file_path = "";
	Messenger messenger;
	int progress = 50;
	Notification notification;
	NotificationManager notificationManager;

	/*
	 * This set of command executes whenever the service is started
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Log.d("FileClientService", "onStartCommand");
		SERVERIP = intent.getStringExtra("ServerIP");
		Log.d("FileClientService", "File Sending to" + SERVERIP);
		file_path = intent.getStringExtra("file_path");
		Bundle extras = intent.getExtras();
		messenger = (Messenger) extras.get("handler");

		// Creates a notification to show the progress of a transfer of a file
		// in the status bar, demonstrates remote views too

		Intent notificationIntent = new Intent(this, FileTransferProgress.class);
		final PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, notificationIntent, 0);

		notification = new Notification(R.drawable.abc,
				"Share Point Downloading...", System.currentTimeMillis());
		notificationManager = (NotificationManager) getApplicationContext()
				.getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
		notification.flags = notification.flags
				| Notification.FLAG_ONGOING_EVENT;
		notification.contentView = new RemoteViews(getApplicationContext()
				.getPackageName(), R.layout.download_progress);
		notification.contentIntent = pendingIntent;
		notification.contentView.setImageViewResource(R.id.status_icon,
				R.drawable.abc);
		notification.contentView.setTextViewText(R.id.status_text, "Status");
		notification.contentView.setProgressBar(R.id.status_progress, 100,
				progress, false);

		notificationManager.notify(42, notification);

		file = new File(file_path);
		/*
		 * This thread starts transfer of file service
		 */
		Thread cThread = new Thread(new ClientFileThread());
		cThread.start();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/*
	 * This class creates a thread that initiates the transfer of a file by
	 * implementing runnables, handlers and messages
	 */
	public class ClientFileThread implements Runnable {

		/* this function is executed when the thread starts */
		public void run() {
			try {
				try {
					/* Create a socket for the file */
					fileSocket = new Socket(SERVERIP, 8890);
					// Log.d("ClientActivity", "C: Sending command.");
					DataInputStream din = new DataInputStream(
							fileSocket.getInputStream());
					String result = din.readUTF();
					Log.d("FileClientService", "Value of Result is " + result);
					/* Initiate file transfer */
					if (result.equals("accepted")) {
						DataOutputStream dout = new DataOutputStream(
								fileSocket.getOutputStream());
						String fileName = file.getName();
						// Log.d("ClientActivity", fileName);
						dout.writeUTF(fileName);
						FileInputStream fileIS = new FileInputStream(file);
						int fileLength = (int) file.length();
						dout.writeInt(fileLength);
						byte[] buf = new byte[64 * 1024];
						int len = 0;
						int sum = 0;
						while ((len = fileIS.read(buf)) != -1) {
							Log.d("ClientFileService", "Sending File...");
							sum = sum + len;
							progress = (sum / fileLength) * 100;
							dout.write(buf, 0, len);
							notification.contentView.setProgressBar(
									R.id.status_progress, 100, progress, false);
							// inform the progress bar of updates in progress
							notificationManager.notify(42, notification);
						}
						Message msg1 = Message.obtain();
						msg1.obj = "File Sent:"
								+ Environment.getExternalStorageDirectory()
								+ "/" + fileName;
						messenger.send(msg1);
						Log.d("ClientFileService", "File Sent..");
						/* Close all connections */
						dout.flush();
						fileIS.close();
						dout.close();
					}

					if (result.equals("denied")) {
						Log.d("ClientFileService", "Request Denied");

					}
				} catch (NullPointerException e) {
					Log.e("ClientActivity", "S: Error", e);
					Toast.makeText(getApplicationContext(),
							"Error Sending File!!!", 2000).show();
				}

			} catch (Exception e) {
				Log.e("ClientFileService", "C: Error", e);

			}
		}
	}
}
